package com.fjnldx.mes.service.productionFigures;

import com.fjnldx.mes.domain.domainReq.*;
import com.fjnldx.mes.domain.domainRes.*;
import com.fjnldx.mes.domain.pojo.MesNewscjh;
import com.fjnldx.mes.mapper.productionFigures.ProductionFiguresMapper;
import com.fjnldx.mes.utils.Common;
import com.fjnldx.mes.utils.ExcelUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class ProductionFiguresService {

    @Autowired
    private Common common;
    @Autowired
    private ProductionFiguresMapper productionFiguresMapper;

    /**
     * 历史轨迹数据实时查询
     *
     * @param dateSectionReq
     * @return
     */
    public Result getHistoryTrackData(DateSectionReq dateSectionReq) {
        LocalDate beginDate = dateSectionReq.getBeginDate();
        LocalDate endDate = dateSectionReq.getEndDate();
        LocalDateTime beginTime = beginDate.atTime(LocalTime.MIN);
        LocalDateTime endTime = endDate.atTime(LocalTime.MIN);
        List<XsHistoryCharsResult> xsHistoryCharsResultList = new ArrayList<>();
        List<String> jtList = dateSectionReq.getJt();

        // 获取开始日期和结束日期中的每个日期
        List<String> days = common.getDaysBySection(beginTime, endTime);
        DateSectionQueryReq dateSectionQueryReq = new DateSectionQueryReq();
        dateSectionQueryReq.setDateSectionReq(dateSectionReq);
        for (String day : days) {
            String tableName = "history_xs_" + day;
            // 查询这个日期是否有数据
            Integer count = productionFiguresMapper.isHaveDataByXs(tableName);
            if (count > 0) {
                // 获取日期的时间点
                LocalDateTime beginTimeByPointTime = LocalDateTime.of(beginTime.toLocalDate(), LocalTime.MIN);
                LocalDateTime endTimeByPointTime = LocalDateTime.of(endTime.toLocalDate(), LocalTime.MAX);
                List<String> pointInTimes = common.getPointInTimes(beginTimeByPointTime, endTimeByPointTime);
                // 根据时间点查询数据
                for (int i = 0; i < pointInTimes.size(); i++) {
                    List<XsHistoryChars> xsHistoryCharsList = new ArrayList<>();
                    String pointInTime = pointInTimes.get(i);
                    dateSectionQueryReq.setPointInTime(pointInTime);
                    dateSectionQueryReq.setTableName(tableName);
                    LocalDateTime pointInTimeLocalDate = LocalDateTime.parse(pointInTime, DateTimeFormatter.ofPattern("yyyyMMddHHmm"));
                    for (String jt : jtList) {
                        dateSectionQueryReq.setDevSn(jt);
                        XsHistory xsHistory = productionFiguresMapper.getHistoryTrackData(dateSectionQueryReq);
                        XsHistoryChars xsHistoryChars = new XsHistoryChars();
                        // 如果查询的时间超过了现在, 则不在取上个时刻的数据
                        if (pointInTimeLocalDate.compareTo(LocalDateTime.now()) < 1) {
                            if (xsHistory == null && i != 0) {
                                dateSectionQueryReq.setPointInTime(pointInTimes.get(i - 1));
                                xsHistory = productionFiguresMapper.getHistoryTrackData(dateSectionQueryReq);
                                dateSectionQueryReq.setPointInTime(pointInTime);
                            }
                        }
                        xsHistoryChars.setDevSn(jt);
                        xsHistoryChars.setXsHistoryResult(xsHistory == null ? new XsHistory() : xsHistory);
                        xsHistoryCharsList.add(xsHistoryChars);
                    }
                    XsHistoryCharsResult xsHistoryCharsResult = new XsHistoryCharsResult();
                    xsHistoryCharsResult.setTime(common.dateTimeFormat(pointInTime, "yyyyMMddHHmm", "yyyy-MM-dd HH:mm"));
                    xsHistoryCharsResult.setXsHistoryCharsResultList(xsHistoryCharsList);
                    xsHistoryCharsResultList.add(xsHistoryCharsResult);
                }
            }
        }
        return Result.success(xsHistoryCharsResultList);
    }

    /**
     * 历史轨迹数据表格查询
     *
     * @param dateSectionReq
     * @return
     */
    public Result getHistoryTrackDataByPage(DateSectionReq dateSectionReq, PageRequest pageRequest) {
        LocalDate beginDate = dateSectionReq.getBeginDate();
        LocalDate endDate = dateSectionReq.getEndDate();
        LocalDateTime beginTime = beginDate.atTime(LocalTime.MIN);
        LocalDateTime endTime = endDate.atTime(LocalTime.MIN);
        List<String> tables = new ArrayList<>();
        // 获取开始日期和结束日期中的每个日期
        List<String> days = common.getDaysBySection(beginTime, endTime);
        DateSectionPageQueryReq dateSectionQueryReq = new DateSectionPageQueryReq();
        dateSectionQueryReq.setDateSectionReq(dateSectionReq);
        for (String day : days) {
            String tableName = "history_xs_" + day;
            // 查询这个日期是否有数据
            Integer count = productionFiguresMapper.isHaveDataByXs(tableName);
            if (count > 0) {
                tables.add(tableName);
            }
        }
        dateSectionQueryReq.setTables(tables);
        dateSectionQueryReq.getDateSectionReq().setEndDate(endDate.plusDays(1));
        PageHelper.startPage(pageRequest.getPageNum(), pageRequest.getPageSize());
        List<Map<String, String>> xsHistory = new ArrayList<>();
        if(tables.size() != 0){
           xsHistory = productionFiguresMapper.getHistoryTrackDataByPage(dateSectionQueryReq);
        }
        return Result.success(new PageInfo<>(xsHistory));
    }

    /**
     * 查询历史用工数据
     */
    public Result queryHistoricalEmployment(HistoricalEmployment historicalEmployment) {
        try {
            List<HistoricalEmployment> historicalEmployments = productionFiguresMapper.queryHistoricalEmployment(historicalEmployment);
            int i = productionFiguresMapper.queryTotalHistoricalEmployment(historicalEmployment);
            ResultObject<HistoricalEmployment> res = new ResultObject<>();
            res.setDataList(historicalEmployments);
            res.setTotal(i);
            return Result.success(res);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error();
        }
    }

    /**
     * 历史数据查询
     */
    public Result queryHistoricalWorkersData(MesNewscjh mesNewscjh) {
        try {
            List<MesNewscjh> mesNewscjhs = productionFiguresMapper.queryHistoricalWorkersData(mesNewscjh);
            int i = productionFiguresMapper.queryTotalHistoricalWorkersData(mesNewscjh);
            MesNewscjhRes res = new MesNewscjhRes();
            res.setDataList(mesNewscjhs);
            res.setTotal(i);
            return Result.success(res);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error();
        }
    }

    /**
     * 导出历史数据查询Excel
     *
     * @param request
     * @param response
     * @throws Exception
     */
    public void exportHistoricalWorkersData(HttpServletRequest request, HttpServletResponse response) throws Exception {
        MesNewscjh mesNewscjh = new MesNewscjh();
        mesNewscjh.setSize(-1);
        //获取数据
        List<MesNewscjh> list = productionFiguresMapper.queryHistoricalWorkersData(mesNewscjh);

        //excel标题
        String[] title = {"组织", "车间", "车台", "开班时间", "班次", "效率", "原料", "开台时间", "停台时间", "挡车工"};

        //excel文件名
        String fileName = "历史数据查询" + System.currentTimeMillis() + ".xls";

        //sheet名
        String sheetName = "历史数据查询";

        String[][] content = new String[list.size()][title.length];
        for (int i = 0; i < list.size(); i++) {
            MesNewscjh obj = list.get(i);
            content[i][0] = obj.getOrg();
            content[i][1] = obj.getCj();
            content[i][2] = obj.getDevSn();
            content[i][3] = obj.getKbsj() == null ? "" : obj.getKbsj().toString();
            content[i][4] = obj.getBc();
            content[i][5] = obj.getXiaolv();
            content[i][6] = obj.getYl();
            content[i][7] = obj.getKtsj() == null ? "" : obj.getTtsj().toString();
            content[i][8] = obj.getTtsj() == null ? "" : obj.getTtsj().toString();
            content[i][9] = obj.getDcg();
        }

        //创建HSSFWorkbook
        HSSFWorkbook wb = ExcelUtil.getHSSFWorkbook(sheetName, title, content, null);

        //响应到客户端
        try {
            common.setResponseHeader(response, fileName);
            OutputStream os = response.getOutputStream();
            wb.write(os);
            os.flush();
            os.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
